import requests


class MalwareConfigClient:

    class __URL:
        Test = "https://malwareconfig.com/api/test/"
        Search = "https://malwareconfig.com/api/search/"
        View = "https://malwareconfig.com/api/file/config/"
        Upload = "https://malwareconfig.com/api/upload/"

    def __init__(self, api_key, action, debug=False):
        self.__api_key = api_key
        self.__debug = debug
        self.logger = action.logger

    ''' Tests the connection to MalwareConfig. '''
    def test_client_connection(self):
        values = {"apikey": self.__api_key}
        request = requests.post(self.__URL.Test, data=values)
        json = request.json()

        if self.__debug:
            self.logger.info("TestClientConnection: Got response")
        return json

    ''' Searches for a config based on type and search term. '''
    def search_config(self, search_type, term):
        values = {"apikey": self.__api_key, "search_word": term, "search_type": search_type}
        url = "{base_url}{type}/".format(base_url=self.__URL.Search, type=search_type)
        request = requests.post(url, data=values, verify=False)

        if self.__debug:
            self.logger.info("SearchConfig: Received status code: {code}".format(code=request.status_code))

        json = request.json()
        return json

    ''' Views the configs for a list of MD5 hashes. '''
    def view_config(self, hashes):
        formatted_hashes = ",".join(hashes)  # Combine hashes into a single string to pass to the API
        values = {"apikey": self.__api_key, "hashes": formatted_hashes}
        request = requests.post(self.__URL.View, data=values)
        if self.__debug:
            self.logger.info("ViewConfig: Received status code: {code}".format(code=request.status_code))

        json = request.json()
        return json

    ''' Uploads a file and returns the config for it. '''
    def upload_file(self, file):
        values = {"apikey": self.__api_key}
        file_params = {"file_submit": file}
        request = requests.post(self.__URL.Upload, data=values, files=file_params)
        json = request.json()

        if self.__debug:
            self.logger.info("UploadFile: ")
        return json
